<template>
  <el-dialog
    :model-value="visible"
    title="安全检查"
    width="800px"
    @update:model-value="$emit('close')"
  >
    <div class="security-check">
      <!-- 检查进度 -->
      <div v-if="checking" class="checking-progress">
        <el-progress :percentage="progress" :status="progressStatus" />
        <p class="progress-text">{{ progressText }}</p>
      </div>

      <!-- 检查结果 -->
      <div v-else class="check-results">
        <!-- 总体安全评分 -->
        <div class="security-score">
          <h3>安全评分</h3>
          <div class="score-display">
            <div class="score-circle" :class="getScoreClass(overallScore)">
              <span class="score-value">{{ overallScore }}</span>
              <span class="score-total">/100</span>
            </div>
            <div class="score-text">
              <p class="score-level">{{ getScoreLevel(overallScore) }}</p>
              <p class="score-desc">{{ getScoreDescription(overallScore) }}</p>
            </div>
          </div>
        </div>

        <!-- 检查项目 -->
        <div class="check-items">
          <h3>检查详情</h3>
          
          <!-- 弱密码检查 -->
          <div class="check-item">
            <div class="item-header">
              <el-icon :class="weakPasswords.length > 0 ? 'danger' : 'success'">
                <component :is="weakPasswords.length > 0 ? 'WarningFilled' : 'SuccessFilled'" />
              </el-icon>
              <span class="item-title">弱密码检查</span>
              <span class="item-count" v-if="weakPasswords.length > 0">
                发现 {{ weakPasswords.length }} 个弱密码
              </span>
            </div>
            <div v-if="weakPasswords.length > 0" class="item-content">
              <div v-for="account in weakPasswords" :key="account.id" class="weak-item">
                <span class="account-name">{{ account.title }}</span>
                <span class="strength-label">{{ getStrengthLabel(account.strength) }}</span>
              </div>
            </div>
          </div>

          <!-- 重复密码检查 -->
          <div class="check-item">
            <div class="item-header">
              <el-icon :class="duplicatePasswords.length > 0 ? 'warning' : 'success'">
                <component :is="duplicatePasswords.length > 0 ? 'Warning' : 'SuccessFilled'" />
              </el-icon>
              <span class="item-title">重复密码检查</span>
              <span class="item-count" v-if="duplicatePasswords.length > 0">
                发现 {{ duplicatePasswords.length }} 组重复密码
              </span>
            </div>
            <div v-if="duplicatePasswords.length > 0" class="item-content">
              <div v-for="group in duplicatePasswords" :key="group.password" class="duplicate-group">
                <div class="duplicate-header">相同密码的账号：</div>
                <div class="duplicate-accounts">
                  <span v-for="account in group.accounts" :key="account.id" class="account-tag">
                    {{ account.title }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 密码过期检查 -->
          <div class="check-item">
            <div class="item-header">
              <el-icon :class="oldPasswords.length > 0 ? 'warning' : 'success'">
                <component :is="oldPasswords.length > 0 ? 'Clock' : 'SuccessFilled'" />
              </el-icon>
              <span class="item-title">密码时效检查</span>
              <span class="item-count" v-if="oldPasswords.length > 0">
                {{ oldPasswords.length }} 个密码超过6个月未更新
              </span>
            </div>
            <div v-if="oldPasswords.length > 0" class="item-content">
              <div v-for="account in oldPasswords" :key="account.id" class="old-item">
                <span class="account-name">{{ account.title }}</span>
                <span class="last-updated">上次更新：{{ formatDate(account.updatedAt) }}</span>
              </div>
            </div>
          </div>

          <!-- 安全建议 -->
          <div class="security-suggestions">
            <h4>安全建议</h4>
            <ul>
              <li v-if="weakPasswords.length > 0">
                建议为弱密码账号生成更强的密码
              </li>
              <li v-if="duplicatePasswords.length > 0">
                为使用相同密码的账号设置不同的密码
              </li>
              <li v-if="oldPasswords.length > 0">
                定期更新密码，建议每3-6个月更换一次
              </li>
              <li v-if="overallScore >= 90">
                密码安全状况良好，继续保持！
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!checking" @click="startCheck">重新检查</el-button>
        <el-button type="primary" @click="$emit('close')">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { WarningFilled, SuccessFilled, Warning, Clock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import zxcvbn from 'zxcvbn'

const props = defineProps({
  visible: Boolean
})

const emit = defineEmits(['close'])

const accountsStore = useAccountsStore()

// 检查状态
const checking = ref(false)
const progress = ref(0)
const progressText = ref('')
const progressStatus = ref('')

// 检查结果
const overallScore = ref(0)
const weakPasswords = ref([])
const duplicatePasswords = ref([])
const oldPasswords = ref([])

// 开始安全检查
const startCheck = async () => {
  checking.value = true
  progress.value = 0
  progressStatus.value = 'active'
  
  try {
    // 步骤1：检查弱密码
    progressText.value = '正在检查密码强度...'
    await checkWeakPasswords()
    progress.value = 33

    // 步骤2：检查重复密码
    progressText.value = '正在检查重复密码...'
    await checkDuplicatePasswords()
    progress.value = 66

    // 步骤3：检查密码时效
    progressText.value = '正在检查密码时效...'
    await checkOldPasswords()
    progress.value = 90

    // 步骤4：计算综合评分
    progressText.value = '正在计算安全评分...'
    calculateOverallScore()
    progress.value = 100
    progressStatus.value = 'success'

    // 延迟显示结果
    setTimeout(() => {
      checking.value = false
      ElMessage.success('安全检查完成')
    }, 500)

  } catch (error) {
    console.error('安全检查失败:', error)
    progressStatus.value = 'exception'
    progressText.value = '检查失败，请重试'
    ElMessage.error('安全检查失败')
  }
}

// 检查弱密码
const checkWeakPasswords = async () => {
  weakPasswords.value = []
  
  for (const account of accountsStore.accounts) {
    if (account.password) {
      // 使用zxcvbn检查密码强度
      const result = zxcvbn(account.password)
      account.strength = result.score
      
      // 强度小于3的视为弱密码
      if (result.score < 3) {
        weakPasswords.value.push(account)
      }
    }
  }
  
  // 模拟异步操作
  await new Promise(resolve => setTimeout(resolve, 800))
}

// 检查重复密码
const checkDuplicatePasswords = async () => {
  duplicatePasswords.value = []
  const passwordGroups = {}
  
  // 按密码分组
  for (const account of accountsStore.accounts) {
    if (account.password) {
      if (!passwordGroups[account.password]) {
        passwordGroups[account.password] = []
      }
      passwordGroups[account.password].push(account)
    }
  }
  
  // 找出重复的密码组
  for (const [password, accounts] of Object.entries(passwordGroups)) {
    if (accounts.length > 1) {
      duplicatePasswords.value.push({
        password,
        accounts
      })
    }
  }
  
  await new Promise(resolve => setTimeout(resolve, 800))
}

// 检查密码时效
const checkOldPasswords = async () => {
  oldPasswords.value = []
  const sixMonthsAgo = new Date()
  sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6)
  
  for (const account of accountsStore.accounts) {
    const updateDate = new Date(account.updatedAt)
    if (updateDate < sixMonthsAgo) {
      oldPasswords.value.push(account)
    }
  }
  
  await new Promise(resolve => setTimeout(resolve, 800))
}

// 计算综合评分
const calculateOverallScore = () => {
  const totalAccounts = accountsStore.accounts.length
  if (totalAccounts === 0) {
    overallScore.value = 100
    return
  }
  
  let score = 100
  
  // 弱密码扣分
  score -= (weakPasswords.value.length / totalAccounts) * 40
  
  // 重复密码扣分
  const duplicateCount = duplicatePasswords.value.reduce((sum, group) => sum + group.accounts.length, 0)
  score -= (duplicateCount / totalAccounts) * 30
  
  // 过期密码扣分
  score -= (oldPasswords.value.length / totalAccounts) * 20
  
  overallScore.value = Math.max(0, Math.round(score))
}

// 获取评分等级
const getScoreLevel = (score) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '一般'
  if (score >= 60) return '较差'
  return '危险'
}

// 获取评分描述
const getScoreDescription = (score) => {
  if (score >= 90) return '您的密码安全状况非常好'
  if (score >= 80) return '密码安全状况良好，有小幅改进空间'
  if (score >= 70) return '密码安全状况一般，建议加强'
  if (score >= 60) return '密码安全状况较差，需要改进'
  return '密码安全状况危险，请立即改进'
}

// 获取评分样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 80) return 'good'
  if (score >= 70) return 'fair'
  if (score >= 60) return 'poor'
  return 'danger'
}

// 获取密码强度标签
const getStrengthLabel = (strength) => {
  const labels = ['极弱', '弱', '一般', '强', '很强']
  return labels[strength] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 监听对话框显示
watch(() => props.visible, (newVal) => {
  if (newVal) {
    startCheck()
  }
})

// 组件挂载时如果对话框已显示则开始检查
onMounted(() => {
  if (props.visible) {
    startCheck()
  }
})
</script>

<style scoped>
.security-check {
  min-height: 400px;
}

.checking-progress {
  text-align: center;
  padding: 60px 20px;
}

.progress-text {
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

.check-results {
  padding: 20px;
}

.security-score {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.score-display {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 15px;
}

.score-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  position: relative;
}

.score-circle.excellent {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  color: white;
}

.score-circle.good {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
}

.score-circle.fair {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
  color: white;
}

.score-circle.poor {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  color: white;
}

.score-circle.danger {
  background: linear-gradient(135deg, #f56c6c, #ff4757);
  color: white;
}

.score-value {
  font-size: 24px;
  line-height: 1;
}

.score-total {
  font-size: 12px;
  opacity: 0.8;
}

.score-text {
  flex: 1;
}

.score-level {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 5px 0;
}

.score-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.check-items h3 {
  margin-bottom: 20px;
  color: #333;
}

.check-item {
  margin-bottom: 25px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #e6e6e6;
}

.item-header .el-icon.success {
  color: #67c23a;
}

.item-header .el-icon.warning {
  color: #e6a23c;
}

.item-header .el-icon.danger {
  color: #f56c6c;
}

.item-title {
  font-weight: bold;
  flex: 1;
}

.item-count {
  color: #f56c6c;
  font-size: 14px;
}

.item-content {
  padding: 15px 20px;
}

.weak-item, .old-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.weak-item:last-child, .old-item:last-child {
  border-bottom: none;
}

.account-name {
  font-weight: 500;
}

.strength-label {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  background: #f56c6c;
  color: white;
}

.last-updated {
  color: #999;
  font-size: 14px;
}

.duplicate-group {
  margin-bottom: 15px;
  padding: 10px;
  background: #fff9e6;
  border-radius: 4px;
}

.duplicate-header {
  font-weight: bold;
  margin-bottom: 8px;
  color: #e6a23c;
}

.duplicate-accounts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.account-tag {
  padding: 4px 8px;
  background: #e6a23c;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.security-suggestions {
  margin-top: 30px;
  padding: 20px;
  background: #f0f9ff;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.security-suggestions h4 {
  margin: 0 0 15px 0;
  color: #409eff;
}

.security-suggestions ul {
  margin: 0;
  padding-left: 20px;
}

.security-suggestions li {
  margin-bottom: 8px;
  color: #666;
}

.dialog-footer {
  text-align: right;
}
</style>
